package scau.filesystem.util.file;

import java.util.ArrayList;
import java.util.List;

public class FileDiscControl extends FileControlImpl {
	
	public static String DISCFILE = "config/zichaoyang.dat";
	
	public static String registerMsgStr = "11111111";
	
	public byte registerMsgByte = (byte)-1;
	
	public void registerBlock(int blockIndex){
		String message = readFromFile(blockIndex/64);
		byte[] bites = DataConversion.convertToByte(message);
		int index = blockIndex > 63 ? blockIndex-64:blockIndex;
		bites[index] = registerMsgByte;
		writeToFile(blockIndex/64, bites);
	}
	
	public int registerBlock(){
		int index = searchEmptyBlock();
		if(index < 0)
			return -1;
		registerBlock(index);
		return index;
	}
	
	public void changeBlockContent(int blocks, int msg){
		int[] FAT = getFAT();
		FAT[blocks] = msg;
		byte[] FAT1 = new byte[64];
		byte[] FAT2 = new byte[64];
		for(int i=0;i<64;i++){
			FAT1[i] = (byte)FAT[i];
			FAT2[i] = (byte)FAT[i+64];
		}
		writeToFile(0, FAT1);
		writeToFile(1, FAT2);
	}
	
	public void ungisterBlock(int blockIndex){
		int[] FAT = getFAT();
		Integer[] blockIndexes = getFileBlocks(blockIndex);
		clearBlock(blockIndexes);
		while(blockIndex != -1 && blockIndex != 0){
			clearBlock(blockIndex);
			blockIndex = FAT[blockIndex];
		}
	}
	
	public void clearBlock(Integer[] bolokIndex){
		byte[] FAT1 = DataConversion.convertToByte(readFromFile(0));
		byte[] FAT2 = DataConversion.convertToByte(readFromFile(1));
		for(int index : bolokIndex){
			if(index > 63){
				FAT2[index-64] = 0; 
			}else{
				FAT1[index] = 0;
			}
		}
		writeToFile(0, FAT1);
		writeToFile(1, FAT2);
	}
	
	public void clearBlock(int blockIndex){
		String message = readFromFile(blockIndex);
		byte[] bites = DataConversion.convertToByte(message);
		for(int i=0;i<bites.length;i++){
			bites[i] = 0;
		}
		writeToFile(blockIndex, bites);
	}
	
	public Integer[] getFileBlocks(int StartBlock){
		List<Integer> list = new ArrayList<>();
		int[] FAT = getFAT();
		while(StartBlock != -1 && StartBlock != 0){
			list.add(StartBlock);
			StartBlock = FAT[StartBlock];
		}
		if(StartBlock == 0)
			return null;
		Integer[] a = new Integer[list.size()];
		return list.toArray(a);
	}
	
	private int[] getFAT(){
		byte[] FAT1 = DataConversion.convertToByte(readFromFile(0));
		byte[] FAT2 = DataConversion.convertToByte(readFromFile(1));
		int[] FAT = new int[128];
		for(int i=0;i<64;i++){
			FAT[i] = FAT1[i];
			FAT[i+64] = FAT2[i];
		}
		return FAT;
	}
	
	public static void main(String[] args) {
		FileDiscControl control = new FileDiscControl();
		control.path = DISCFILE;
		control.initFile(DISCFILE);
	}

}
